/*
 * Copyright (c) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "iot_cloud.h"
#include "iot_profile.h"
#include "cJSON.h"
#include <stdint.h>
#include <stddef.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

static int SetDetectionStatus = DETECT_OFF;

void SetDetectionStatusValue(int value)
{
    RaiseLog(LOG_LEVEL_INFO, "set SetDetectionStatus ->%d", value);
    SetDetectionStatus = value;
}

int GetDetectionStatusValue(void)
{
    return SetDetectionStatus;
}


/**
 * @brief we make the data to a json string and send it to the iot cloud engine
 *
 */
int IotProfile_Report(int Status)
{
	int ret = -1;
	char *jsonString;
	IotProfileService	 service;
	IotProfileKV  kvBeepStatus;

	/* package the data */
	service.eventTime = NULL;
	service.serviceID = "SmartSafe";
	service.propertyLst = &kvBeepStatus;
	service.nxt = NULL;

	kvBeepStatus.key = "VibrationValue";
	kvBeepStatus.value = Status ? "ON" : "OFF";
	kvBeepStatus.type = IOT_PROFILE_KEY_DATATYPE_STRING;
	kvBeepStatus.nxt = NULL;

	jsonString = IoTProfilePackage(&service);
	if ( NULL != jsonString) {
		RaiseLog(LOG_LEVEL_INFO,"jsonString:%s", jsonString);
		ret = CLOUD_ReportMsg(jsonString);
		free(jsonString);
	} else {
		RaiseLog(LOG_LEVEL_ERR,"format the report message error");
	}
	return ret;
}

int CLOUD_CommandCallBack(const char *jsonString)
{
    cJSON *objRoot = NULL;
    cJSON *objCmdName = NULL;
    cJSON *objParas = NULL;
    cJSON *objPara = NULL;

    int ret = -1;
    if (jsonString == NULL) {
        return ret;
    }
    RaiseLog(LOG_LEVEL_INFO,"jsonString -> %s", jsonString);
    if ((objRoot = cJSON_Parse(jsonString)) == NULL) {
        RaiseLog(LOG_LEVEL_INFO,"could not parse the payload\r\n");
        goto EXIT_JSONPARSE;
    }

    if ((objParas = cJSON_GetObjectItem(objRoot, "paras")) == NULL) {
        RaiseLog(LOG_LEVEL_INFO,"Could not get paras in json");
        return ret;
    }

    if ((objPara = cJSON_GetObjectItem(objParas, "VibrationStatus")) != NULL) {
        if (0 == strcmp(cJSON_GetStringValue(objPara), "ON")) {
            SetDetectionStatus = DETECT_ON;
            RaiseLog(LOG_LEVEL_INFO,"IS ON");
        }
        else {
            RaiseLog(LOG_LEVEL_INFO,"IS OFF");
            IotProfile_Report(DETECT_OFF);
        }
    }

EXIT_JSONPARSE:
    if (objRoot != NULL) {
        cJSON_Delete(objRoot);
    }
    return 0;
}





